{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 标准try语法\n",
    "try:\n",
    "    print(\"尝试执行代码\")\n",
    "    1 / 0\n",
    "except Exception as e:\n",
    "    print(\"捕获到异常后执行\")\n",
    "    print(e)\n",
    "else:\n",
    "    print(\"没有异常后执行\")\n",
    "finally:\n",
    "    print(\n",
    "        \"都会执行\"\n",
    "    )  # 适合在打开大型数据库后, 不管有没有报错都关掉, 防止造成额外的内存开销"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打印更详细的异常\n",
    "import traceback\n",
    "\n",
    "try:\n",
    "    print(\"尝试执行代码\")\n",
    "    1 / 0\n",
    "except Exception as e:\n",
    "    print(\"捕获到异常后执行\")\n",
    "    print(f\"Error:{e}\")\n",
    "    traceback.print_exc()\n",
    "else:\n",
    "    print(\"没有异常后执行\")\n",
    "finally:\n",
    "    print(\"都会执行\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 针对不同的异常进行不同的操作\n",
    "try:\n",
    "    print(\"尝试执行代码\")\n",
    "    1 / 0  # type: ignore\n",
    "    print(a)  # type: ignore\n",
    "    int(\"a\")\n",
    "except ZeroDivisionError as e:  # 代表0作为除数的异常\n",
    "    print(f\"ZeroDivisionError: {e}\")\n",
    "except NameError as e:\n",
    "    print(f\"NameError: {e}\")\n",
    "except ValueError as e:  # 代表值错误\n",
    "    print(f\"ValueError: {e}\")\n",
    "except Exception as e:  # Exception代表所有异常\n",
    "    print(f\"Exception: {e}\")\n",
    "else:\n",
    "    print(\"没有异常后执行\")\n",
    "finally:\n",
    "    print(\"都会执行\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 主动抛出异常\n",
    "class MyError(BaseException):  # 定义一个异常类型,基于BaseException\n",
    "    def __init__(self, arg1, arg2):\n",
    "        self.arg1 = arg1\n",
    "        self.arg2 = arg2\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"自定义的Error{self.arg1,self.arg2}\"\n",
    "\n",
    "\n",
    "arg1 = 1\n",
    "arg2 = 0\n",
    "if arg2 == 0:\n",
    "    raise MyError(arg1, arg2)  # 主动抛出异常,使程序停止运行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 主动抛出异常,并被捕获\n",
    "class MyError(BaseException):  # 定义一个异常类型,基于BaseException\n",
    "    def __init__(self, arg1, arg2):\n",
    "        self.arg1 = arg1\n",
    "        self.arg2 = arg2\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"自定义的Error{self.arg1,self.arg2}\"\n",
    "\n",
    "\n",
    "try:\n",
    "    arg1 = 1\n",
    "    arg2 = 0\n",
    "    if arg2 == 0:\n",
    "        raise MyError(arg1, arg2)\n",
    "        # 即使被try包裹,如果没有写对应的except,也会停止运行,而不会被Excption捕获\n",
    "    arg1 / arg2\n",
    "except MyError as e:\n",
    "    print(\"被MyError捕获\")\n",
    "    print(e)\n",
    "except Exception as e:  # 由于MyError没有继承自Exception,顾无法被Exception捕获\n",
    "    print(\"被Exception捕获\")\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自定义可被Exception捕获的异常\n",
    "class MyError(Exception):  # 使其继承自Exception\n",
    "    def __init__(self, arg1, arg2):\n",
    "        self.arg1 = arg1\n",
    "        self.arg2 = arg2\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"自定义的Error{self.arg1,self.arg2}\"\n",
    "\n",
    "\n",
    "try:\n",
    "    arg1 = 1\n",
    "    arg2 = 0\n",
    "    if arg2 == 0:\n",
    "        raise MyError(arg1, arg2)\n",
    "    arg1 / arg2\n",
    "except Exception as e:\n",
    "    print(\"被Exception捕获\")\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 断点\n",
    "class MyError(Exception):  # 使其继承自Exception\n",
    "    def __init__(self, arg1, arg2):\n",
    "        self.arg1 = arg1\n",
    "        self.arg2 = arg2\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"自定义的Error{self.arg1,self.arg2}\"\n",
    "\n",
    "\n",
    "try:\n",
    "    arg1 = 1\n",
    "    arg2 = 0\n",
    "    assert arg2 != 0, MyError(\n",
    "        arg1, arg2\n",
    "    )  # 为True时继续,否则抛出异常. 本质与if raise的写法一样, 只是判断条件相反,True则继续,False则抛出\n",
    "except Exception as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "测试Debug\n",
      "[2, 3, 5, 7, 10001]\n",
      "10001\n"
     ]
    }
   ],
   "source": [
    "# 调试程序\n",
    "\n",
    "\n",
    "# 求质数\n",
    "def getPrime(maxNum=10) -> list[int]:\n",
    "    primeNum = list()\n",
    "    i = 2\n",
    "    for i in range(2, maxNum):\n",
    "        j = 2\n",
    "        for j in range(2, i):\n",
    "            if i % j == 0:\n",
    "                break\n",
    "        # 这里的else是:当对应的for循环正常结束(未被break)的时候,执行一次.\n",
    "        # 当排到的数字i不是质数(也就是能被2到i之间的整数整除(也就是余数等于0)),则不将该数字添加到\"质数列\"\n",
    "        else:\n",
    "            primeNum.append(i)\n",
    "    return primeNum\n",
    "\n",
    "\n",
    "print(\"测试Debug\")\n",
    "primeNums = getPrime(10)\n",
    "primeNums.append(10001)\n",
    "print(primeNums)\n",
    "maxPrimeNum = max(primeNums)\n",
    "print(maxPrimeNum)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
